<?php
// 引入密码配置
require_once './key.php';

// 登录API和Cookie验证
class Auth {
    private static $cookieName = 'jsonblog_token';
    private static $tokenExpiry = 86400; // 24小时

    // 验证密码并设置Cookie
    public static function login($password) {
        global $admin_password;
        if ($password === $admin_password) {
            $token = self::generateToken();
            setcookie(self::$cookieName, $token, time() + self::$tokenExpiry, '/');
            return ['success' => true, 'message' => '登录成功'];
        }
        return ['success' => false, 'message' => '密码错误'];
    }

    // 验证Cookie中的token
    public static function isAuthenticated() {
        if (!isset($_COOKIE[self::$cookieName])) {
            return false;
        }

        $token = $_COOKIE[self::$cookieName];
        // 简单的token验证（实际应用中应该更复杂）
        return self::validateToken($token);
    }

    // 登出并清除Cookie
    public static function logout() {
        setcookie(self::$cookieName, '', time() - 3600, '/');
        return ['success' => true, 'message' => '登出成功'];
    }

    // 生成token
    private static function generateToken() {
        global $admin_password;
        $randomString = bin2hex(random_bytes(16));
        $timestamp = time();
        $hash = hash('sha256', $admin_password . $randomString . $timestamp);
        return base64_encode(json_encode([
            'hash' => $hash,
            'timestamp' => $timestamp,
            'random' => $randomString
        ]));
    }

    // 验证token
    private static function validateToken($token) {
        global $admin_password;
        try {
            $data = json_decode(base64_decode($token), true);
            if (!$data || !isset($data['hash'], $data['timestamp'], $data['random'])) {
                return false;
            }

            // 检查是否过期
            if (time() - $data['timestamp'] > self::$tokenExpiry) {
                return false;
            }

            // 重新计算哈希值进行验证
            $validHash = hash('sha256', $admin_password . $data['random'] . $data['timestamp']);
            return $data['hash'] === $validHash;
        } catch (\Exception $e) {
            return false;
        }
    }
}

// 处理登录请求
if (isset($_POST['action']) && $_POST['action'] === 'login') {
    $password = $_POST['password'] ?? '';
    $result = Auth::login($password);
    header('Content-Type: application/json');
    echo json_encode($result);
    exit;
}

// 处理登出请求
if ((isset($_GET['action']) && $_GET['action'] === 'logout') || (isset($_POST['action']) && $_POST['action'] === 'logout')) {
    $result = Auth::logout();
    header('Content-Type: application/json');
    echo json_encode($result);
    exit;
}

// 处理登录状态检查请求
if (isset($_GET['action']) && $_GET['action'] === 'check') {
    $result = ['authenticated' => Auth::isAuthenticated()];
    header('Content-Type: application/json');
    echo json_encode($result);
    exit;
}

// 验证用户是否已登录
if (!Auth::isAuthenticated() && !isset($_GET['action'])) {
    // 如果没有登录且不是登录请求，则返回未授权
    header('HTTP/1.1 401 Unauthorized');
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

class BlogMake {
    private $siteConfig;
    private $blogList;
    private $baseDir;

    // 设置siteConfig的setter方法
    public function setSiteConfig($config) {
        $this->siteConfig = $config;
    }

    public function __construct() {
        $this->baseDir = dirname(__FILE__) . '/';
        $this->loadConfigs();
    }

    private function loadConfigs() {
        // 读取site.json配置
        $siteConfigPath = $this->baseDir . 'static/config/site.json';
        if (file_exists($siteConfigPath)) {
            $this->siteConfig = json_decode(file_get_contents($siteConfigPath), true);
        } else {
            throw new Exception('site.json配置文件不存在');
        }

        // 读取blogList.json配置
        $blogListPath = $this->baseDir . 'static/config/blogList.json';
        if (file_exists($blogListPath)) {
            $this->blogList = json_decode(file_get_contents($blogListPath), true);
        } else {
            throw new Exception('blogList.json配置文件不存在');
        }
    }

    // 生成动态about内容
    public function generateAboutContent() {
        $title = htmlspecialchars($this->siteConfig['title'] ?? '', ENT_QUOTES);
        $interests = $this->siteConfig['interests'] ?? '';
        $skills = $this->siteConfig['skills'] ?? '';
        $selfIntroduction = $this->siteConfig['selfIntroduction'] ?? '';

        $aboutParts = [];
        $aboutParts[] = "<span style=\"color:var(--kw)\">const</span> <span style=\"color:var(--accent)\">{$title}</span> = {<br>";

        // 处理自我介绍注释
        if (!empty($selfIntroduction)) {
            $selfIntroduction = htmlspecialchars($selfIntroduction, ENT_QUOTES);
            $aboutParts[] = "&nbsp;&nbsp;<span style=\"color:var(--cmt)\">/* {$selfIntroduction} */</span><br>";
        }

        // 处理interests（值为#时不生成）
        if ($interests !== '#' && !empty($interests)) {
            // 将兴趣数组转换为带引号的字符串
            if (is_array($interests)) {
                $quotedInterests = array_map(function($item) {
                    return '"' . htmlspecialchars($item, ENT_QUOTES) . '"';
                }, $interests);
                $interestsStr = implode(', ', $quotedInterests);
            } else {
                $interestsStr = htmlspecialchars($interests, ENT_QUOTES);
            }
            $aboutParts[] = "&nbsp;&nbsp;<span style=\"color:var(--kw)\">interests</span>: [<span style=\"color:var(--str)\">{$interestsStr}</span>],<br>";
        }

        // 处理skills（值为#时不生成）
        if ($skills !== '#' && !empty($skills)) {
            // 将技能数组转换为带引号的字符串
            if (is_array($skills)) {
                $quotedSkills = array_map(function($item) {
                    return '"' . htmlspecialchars($item, ENT_QUOTES) . '"';
                }, $skills);
                $skillsStr = implode(', ', $quotedSkills);
            } else {
                $skillsStr = htmlspecialchars($skills, ENT_QUOTES);
            }
            $aboutParts[] = "&nbsp;&nbsp;<span style=\"color:var(--kw)\">skills</span>: [<span style=\"color:var(--str)\">{$skillsStr}</span>]<br>";
        }

        $aboutParts[] = "};";
        return implode('', $aboutParts);
    }

    // 生成首页HTML文件
    public function generateIndexHtml() {
        // 确保生成所有分区数据
        ob_start();
        // 临时设置为不选择任何分区，确保生成所有分区内容
        $_GET['partition'] = null;
        include $this->baseDir . 'templates/index.php';
        $htmlContent = ob_get_clean();

        // 写入index.html文件
        $indexPath = $this->baseDir . 'index.html';
        file_put_contents($indexPath, $htmlContent);
        return $indexPath;
    }

    // 生成分区页面
    public function generatePartitionHtml() {
        $partitionsDir = $this->baseDir . 'Partitions/';
        // 创建Partitions目录（如果不存在）
        if (!is_dir($partitionsDir)) {
            mkdir($partitionsDir, 0755, true);
        }

        $partitions = $this->siteConfig['partitions'] ?? [];
        foreach ($partitions as $partition) {
            $partitionId = $partition['id'];
            $partitionHtmlPath = $partitionsDir . $partitionId . '.html';

            // 设置当前分区
            $_GET['partition'] = $partitionId;

            // 使用partitions.php模板生成HTML
            ob_start();
            include $this->baseDir . 'templates/partitions.php';
            $htmlContent = ob_get_clean();

            file_put_contents($partitionHtmlPath, $htmlContent);
        }
        return count($partitions);
    }

    // 生成帖子页面
    public function generatePosts() {
        $mdDir = $this->baseDir . 'static/md/';
        $postsDir = $this->baseDir . 'posts/';

        // 创建posts目录（如果不存在）
        if (!is_dir($postsDir)) {
            mkdir($postsDir, 0755, true);
        }

        // 获取所有md文件
        $mdFiles = glob($mdDir . '*.md');
        foreach ($mdFiles as $mdFile) {
            // 提取文件ID（假设文件名格式为{id}.md）
            $fileName = basename($mdFile);
            $id = pathinfo($fileName, PATHINFO_FILENAME);
            $postHtmlPath = $postsDir . $id . '.html';

            // 读取markdown内容并解析
            $mdContent = file_get_contents($mdFile);
            $content = $this->parseMarkdown($mdContent);
            //echo "解析Markdown文件：{$mdFile}\n";
            //echo "解析Markdown内容：{$content}\n";

            // 查找对应的博客信息
            $blogInfo = null;
            foreach ($this->blogList as $blog) {
                if ($blog['id'] == $id) {
                    $blogInfo = $blog;
                    break;
                }
            }
            if (!$blogInfo) {
                $blogInfo = ['title' => '未找到标题', 'author' => '未知作者', 'time' => date('Y-m-d')];
            }

            // 使用模板生成HTML
            ob_start();
            include $this->baseDir . 'templates/posts.php';
            $htmlContent = ob_get_clean();

            file_put_contents($postHtmlPath, $htmlContent);
        }
        return count($mdFiles);
    }

    // 解析Markdown
    private function parseMarkdown($markdown) {
        // 标题转换
        $markdown = preg_replace('/^# (.*)$/m', '<h1>$1</h1>', $markdown);
        $markdown = preg_replace('/^## (.*)$/m', '<h2>$1</h2>', $markdown);
        $markdown = preg_replace('/^### (.*)$/m', '<h3>$1</h3>', $markdown);
        $markdown = preg_replace('/^#### (.*)$/m', '<h4>$1</h4>', $markdown);
        $markdown = preg_replace('/^##### (.*)$/m', '<h5>$1</h5>', $markdown);
        $markdown = preg_replace('/^###### (.*)$/m', '<h6>$1</h6>', $markdown);

        // 粗体和斜体
        $markdown = preg_replace('/\*\*(.*?)\*\*/', '<strong>$1</strong>', $markdown);
        $markdown = preg_replace('/\*(.*?)\*/', '<em>$1</em>', $markdown);
        
        // 图片
        $markdown = preg_replace('/!\[(.*?)\]\((.*?)\)/', '<img src="$2" alt="$1">', $markdown);

        // 链接
        $markdown = preg_replace('/\[(.*?)\]\((.*?)\)/', '<a href="$2">$1</a>', $markdown);

        // 段落
        $markdown = '<p>' . preg_replace('/\n\n/', '</p><p>', $markdown) . '</p>';
        $markdown = str_replace('</p><p></p>', '</p>', $markdown); // 处理空段落

        // 代码块
        $markdown = preg_replace('/```(.*?)```/s', '<pre><code>$1</code></pre>', $markdown);

        // 列表
        $markdown = preg_replace('/^\s*-\s+(.*)$/m', '<li>$1</li>', $markdown);
        $markdown = preg_replace('/<li>(.*?)<\/li>/s', '<ul>\n<li>$1</li>\n</ul>', $markdown);
        $markdown = preg_replace('/<ul>(.*?)<\/ul>/s', '<ul>$1</ul>', $markdown);
        $markdown = preg_replace('/<ol>(.*?)<\/ol>/s', '<ol>$1</ol>', $markdown);
        $markdown = preg_replace('/<li>(.*?)<\/li>/s', '<ol>\n<li>$1</li>\n</ol>', $markdown);
        $markdown = preg_replace('/<ol>(.*?)<\/ol>/s', '<ol>$1</ol>', $markdown);
        $markdown = preg_replace('/<ol>(.*?)<\/ol>/s', '<ol>$1</ol>', $markdown);
        $markdown = preg_replace('/<li>(.*?)<\/li>/s', '<ol>\n<li>$1</li>\n</ol>', $markdown);

        // 引用
        $markdown = preg_replace('/^\s*>\s+(.*)$/m', '<blockquote>$1</blockquote>', $markdown);

        // 去除多余的空格和换行符
        $markdown = trim($markdown);
        $markdown = str_replace("\n", "<br>", $markdown);


        return $markdown;
    }
}

// 初始化博客系统
function initBlogSystem() {
    // 检查并创建必要的目录
    $requiredDirs = [dirname(__FILE__) . '/posts', dirname(__FILE__) . '/Partitions', dirname(__FILE__) . '/templates'];
    foreach ($requiredDirs as $dir) {
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
    }
    
    // 检查并创建配置文件
    $siteConfigPath = dirname(__FILE__) . '/static/config/site.json';
    if (!file_exists($siteConfigPath)) {
        $defaultConfig = [
            'title' => '我的博客',
            'description' => '个人博客系统',
            'keywords' => '博客,技术,分享',
            'author' => '博主',
            'url' => 'http://localhost',
            'selfIntroduction' => '欢迎来到我的博客！',
            'partitions' => []
        ];
        file_put_contents($siteConfigPath, json_encode($defaultConfig, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    }
    
    // 检查并创建博客列表文件
    $blogListPath = dirname(__FILE__) . '/static/config/blogList.json';
    if (!file_exists($blogListPath)) {
        file_put_contents($blogListPath, json_encode([], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    }
}

// API - 获取站点配置
function getSiteConfig() {
    // 初始化博客系统
    initBlogSystem();
    
    // 读取配置文件
    $siteConfigPath = dirname(__FILE__) . '/static/config/site.json';
    if (!file_exists($siteConfigPath)) {
        echo json_encode(['success' => false, 'message' => '配置文件不存在']);
        return;
    }
    
    $config = json_decode(file_get_contents($siteConfigPath), true);
    echo json_encode(['success' => true, 'data' => $config]);
}

// API - 保存站点配置
function saveSiteConfig() {
    // 检查是否有配置数据
    if (!isset($_POST['config'])) {
        echo json_encode(['success' => false, 'message' => '未提供配置数据']);
        return;
    }
    
    // 解析配置数据
    $newConfig = json_decode($_POST['config'], true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo json_encode(['success' => false, 'message' => '配置数据格式错误']);
        return;
    }
    
    // 读取现有配置
    $siteConfigPath = dirname(__FILE__) . '/static/config/site.json';
    if (file_exists($siteConfigPath)) {
        $existingConfig = json_decode(file_get_contents($siteConfigPath), true);
    } else {
        $existingConfig = [];
    }
    
    // 合并配置 - 只更新提供的字段
    $config = array_merge($existingConfig, $newConfig);
    
    // 生成动态about内容
    $blogMaker = new BlogMake();
    $blogMaker->setSiteConfig($config);
    $aboutContent = $blogMaker->generateAboutContent();
    $config['about'] = $aboutContent;
    
    // 保存配置文件
    if (file_put_contents($siteConfigPath, json_encode($config, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) !== false) {
        echo json_encode(['success' => true, 'message' => '配置保存成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '配置保存失败']);
    }
}

// API - 获取博客列表
function getBlogList() {
    // 初始化博客系统
    initBlogSystem();
    
    // 读取博客列表文件
    $blogListPath = dirname(__FILE__) . '/static/config/blogList.json';
    if (!file_exists($blogListPath)) {
        echo json_encode(['success' => false, 'message' => '博客列表文件不存在']);
        return;
    }
    
    $blogList = json_decode(file_get_contents($blogListPath), true);
    
    // 按时间倒序排序
    usort($blogList, function($a, $b) {
        return strtotime($b['time']) - strtotime($a['time']);
    });
    
    // 置顶的文章排在前面
    usort($blogList, function($a, $b) {
        if ($a['top'] && !$b['top']) return -1;
        if (!$a['top'] && $b['top']) return 1;
        return 0;
    });
    
    echo json_encode(['success' => true, 'data' => $blogList]);
}

// API - 保存博客列表
function saveBlogList() {
    // 检查是否有博客列表数据
    if (!isset($_POST['blogList'])) {
        echo json_encode(['success' => false, 'message' => '未提供博客列表数据']);
        return;
    }
    
    // 解析博客列表数据
    $blogList = json_decode($_POST['blogList'], true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo json_encode(['success' => false, 'message' => '博客列表数据格式错误']);
        return;
    }
    
    // 保存博客列表文件
    $blogListPath = dirname(__FILE__) . '/static/config/blogList.json';
    if (file_put_contents($blogListPath, json_encode($blogList, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) !== false) {
        echo json_encode(['success' => true, 'message' => '博客列表保存成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '博客列表保存失败']);
    }
}

// API - 获取帖子内容
function getPostContent() {
    // 检查是否有帖子ID
    if (!isset($_POST['id'])) {
        echo json_encode(['success' => false, 'message' => '未提供帖子ID']);
        return;
    }
    
    $id = $_POST['id'];
    $filePath = dirname(__FILE__) . '/static/md/' . $id . '.md';
    
    // 检查文件是否存在
    if (!file_exists($filePath)) {
        echo json_encode(['success' => false, 'message' => '帖子文件不存在']);
        return;
    }
    
    // 读取帖子内容
    $content = file_get_contents($filePath);
    echo json_encode(['success' => true, 'content' => $content]);
}

// API - 保存帖子内容
function savePostContent() {
    // 检查是否有帖子ID和内容
    if (!isset($_POST['id']) || !isset($_POST['content'])) {
        echo json_encode(['success' => false, 'message' => '未提供帖子ID或内容']);
        return;
    }
    
    $id = $_POST['id'];
    $content = $_POST['content'];
    $filePath = dirname(__FILE__) . '/static/md/' . $id . '.md';
    
    // 保存帖子内容
    if (file_put_contents($filePath, $content) !== false) {
        echo json_encode(['success' => true, 'message' => '帖子内容保存成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '帖子内容保存失败']);
    }
}

// API - 删除帖子
function deletePost() {
    // 检查是否有帖子ID
    if (!isset($_POST['id'])) {
        echo json_encode(['success' => false, 'message' => '未提供帖子ID']);
        return;
    }

    $id = $_POST['id'];
    $mdFilePath = dirname(__FILE__) . '/static/md/' . $id . '.md';
    $htmlFilePath = dirname(__FILE__) . '/posts/' . $id . '.html';

    // 删除帖子文件
    $mdDeleted = true;
    if (file_exists($mdFilePath)) {
        $mdDeleted = unlink($mdFilePath);
    }

    // 删除HTML文件
    $htmlDeleted = true;
    if (file_exists($htmlFilePath)) {
        $htmlDeleted = unlink($htmlFilePath);
    }

    if ($mdDeleted && $htmlDeleted) {
        echo json_encode(['success' => true, 'message' => '帖子删除成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '帖子删除失败']);
    }
}

// API - 保存Work
function saveWork() {
    // 读取现有配置
    $siteConfigPath = dirname(__FILE__) . '/static/config/site.json';
    if (!file_exists($siteConfigPath)) {
        echo json_encode(['success' => false, 'message' => '配置文件不存在']);
        return;
    }

    $existingConfig = json_decode(file_get_contents($siteConfigPath), true);
    $works = $existingConfig['works'] ?? [];

    // 获取Work数据
    $workId = '';
    $title = '';
    $description = '';
    $link = '';
    $image = '';

    // 检查是否有workData参数（JSON格式）
    if (isset($_POST['workData'])) {
        $workData = json_decode($_POST['workData'], true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            echo json_encode(['success' => false, 'message' => 'Work数据格式错误']);
            return;
        }
        $workId = $workData['id'] ?? '';
        $title = $workData['title'] ?? '';
        $description = $workData['description'] ?? '';
        // 兼容前端使用的url字段和后端使用的link字段
        $link = $workData['link'] ?? $workData['url'] ?? '';
        $image = $workData['image'] ?? '';
    } else {
        // 从表单数据获取
        $workId = $_POST['id'] ?? '';
        $title = $_POST['title'] ?? '';
        $description = $_POST['description'] ?? '';
        $link = $_POST['link'] ?? '';
        $image = $_POST['image'] ?? '';
    }

    if (empty($title)) {
        echo json_encode(['success' => false, 'message' => 'Work标题不能为空']);
        return;
    }

    if (!empty($workId)) {
            // 更新现有Work
            $found = false;
            foreach ($works as &$work) {
                if ($work['id'] == $workId) {
                    $work['title'] = $title;
                    $work['description'] = $description;
                    // 统一使用url字段
                    $work['url'] = $link;
                    // 移除link字段
                    if (isset($work['link'])) {
                        unset($work['link']);
                    }
                    $work['image'] = $image;
                    $found = true;
                    break;
                }
            }

            if (!$found) {
                echo json_encode(['success' => false, 'message' => '未找到指定的Work']);
                return;
            }
        } else {
            // 添加新Work
            // 生成新ID
            $newId = 1;
            if (!empty($works)) {
                // 确保数组有id列且至少有一个元素
                $ids = array_column($works, 'id');
                if (!empty($ids)) {
                    $newId = max($ids) + 1;
                }
            }

            $works[] = [
                'id' => $newId,
                'title' => $title,
                'description' => $description,
                // 统一使用url字段
                'url' => $link,
                'image' => $image
            ];
        }

    // 更新配置
    $existingConfig['works'] = $works;

    // 保存配置文件
    if (file_put_contents($siteConfigPath, json_encode($existingConfig, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) !== false) {
        echo json_encode(['success' => true, 'message' => 'Work保存成功']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Work保存失败']);
    }
}

// API - 获取Works列表
function getWorksList() {
    // 初始化博客系统
    initBlogSystem();
    
    // 读取配置文件
    $siteConfigPath = dirname(__FILE__) . '/static/config/site.json';
    if (!file_exists($siteConfigPath)) {
        echo json_encode(['success' => false, 'message' => '配置文件不存在']);
        return;
    }
    
    $config = json_decode(file_get_contents($siteConfigPath), true);
    $works = $config['works'] ?? [];
    
    // 统一字段名：确保所有对象使用url字段，不再使用link字段
    foreach ($works as &$work) {
        // 如果有url字段，保留其值；如果没有url但有link，则使用link的值
        if (!isset($work['url']) && isset($work['link'])) {
            $work['url'] = $work['link'];
        }
        // 移除link字段，统一使用url
        if (isset($work['link'])) {
            unset($work['link']);
        }
    }
    
    echo json_encode(['success' => true, 'data' => $works]);
}

// API - 保存Works列表
function saveWorksList() {
    // 检查是否有Works列表数据
    if (!isset($_POST['worksList'])) {
        echo json_encode(['success' => false, 'message' => '未提供Works列表数据']);
        return;
    }
    
    // 解析Works列表数据
    $worksList = json_decode($_POST['worksList'], true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo json_encode(['success' => false, 'message' => 'Works列表数据格式错误']);
        return;
    }
    
    // 统一字段名：确保所有对象使用url字段，不再使用link字段
    foreach ($worksList as &$work) {
        // 如果有url字段，保留其值；如果没有url但有link，则使用link的值
        if (!isset($work['url']) && isset($work['link'])) {
            $work['url'] = $work['link'];
        }
        // 移除link字段，统一使用url
        if (isset($work['link'])) {
            unset($work['link']);
        }
    }
    
    // 读取现有配置
    $siteConfigPath = dirname(__FILE__) . '/static/config/site.json';
    if (!file_exists($siteConfigPath)) {
        echo json_encode(['success' => false, 'message' => '配置文件不存在']);
        return;
    }
    
    $existingConfig = json_decode(file_get_contents($siteConfigPath), true);
    
    // 更新Works列表
    $existingConfig['works'] = $worksList;
    
    // 保存配置文件
    if (file_put_contents($siteConfigPath, json_encode($existingConfig, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) !== false) {
        echo json_encode(['success' => true, 'message' => 'Works列表保存成功']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Works列表保存失败']);
    }
}

// API - 删除Work
function deleteWork() {
    // 检查是否有Work ID
    if (!isset($_POST['id'])) {
        echo json_encode(['success' => false, 'message' => '未提供Work ID']);
        return;
    }

    $id = $_POST['id'];

    // 读取现有配置
    $siteConfigPath = dirname(__FILE__) . '/static/config/site.json';
    if (!file_exists($siteConfigPath)) {
        echo json_encode(['success' => false, 'message' => '配置文件不存在']);
        return;
    }

    $existingConfig = json_decode(file_get_contents($siteConfigPath), true);
    $works = $existingConfig['works'] ?? [];

    // 查找并删除Work
    $newWorks = [];
    foreach ($works as $work) {
        if ($work['id'] != $id) {
            $newWorks[] = $work;
        }
    }

    // 如果Work数量没变，说明没找到要删除的Work
    if (count($newWorks) == count($works)) {
        echo json_encode(['success' => false, 'message' => '未找到指定的Work']);
        return;
    }

    // 更新配置
    $existingConfig['works'] = $newWorks;

    // 保存配置文件
    if (file_put_contents($siteConfigPath, json_encode($existingConfig, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) !== false) {
        echo json_encode(['success' => true, 'message' => 'Work删除成功']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Work删除失败']);
    }
}

// API - 保存分区
function savePartition() {
    // 读取现有配置
    $siteConfigPath = dirname(__FILE__) . '/static/config/site.json';
    if (!file_exists($siteConfigPath)) {
        echo json_encode(['success' => false, 'message' => '配置文件不存在']);
        return;
    }

    $existingConfig = json_decode(file_get_contents($siteConfigPath), true);
    $partitions = $existingConfig['partitions'] ?? [];

    // 获取分区数据
    $partitionId = $_POST['id'] ?? '';
    $title = $_POST['title'] ?? '';
    $description = $_POST['description'] ?? '';

    if (empty($title)) {
        echo json_encode(['success' => false, 'message' => '分区标题不能为空']);
        return;
    }

    if (!empty($partitionId)) {
        // 更新现有分区
        $found = false;
        foreach ($partitions as &$partition) {
            if ($partition['id'] == $partitionId) {
                $partition['title'] = $title;
                $partition['description'] = $description;
                $found = true;
                break;
            }
        }

        if (!$found) {
            echo json_encode(['success' => false, 'message' => '未找到指定的分区']);
            return;
        }
    } else {
        // 添加新分区
        // 生成新ID
        $newId = 1;
        if (!empty($partitions)) {
            $newId = max(array_column($partitions, 'id')) + 1;
        }

        $partitions[] = [
            'id' => $newId,
            'title' => $title,
            'description' => $description
        ];
    }

    // 更新配置
    $existingConfig['partitions'] = $partitions;

    // 保存配置文件
    if (file_put_contents($siteConfigPath, json_encode($existingConfig, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) !== false) {
        echo json_encode(['success' => true, 'message' => '分区保存成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '分区保存失败']);
    }
}

// API - 删除分区
function deletePartition() {
    // 检查是否有分区ID
    if (!isset($_POST['id'])) {
        echo json_encode(['success' => false, 'message' => '未提供分区ID']);
        return;
    }

    $id = $_POST['id'];

    // 读取现有配置
    $siteConfigPath = dirname(__FILE__) . '/static/config/site.json';
    if (!file_exists($siteConfigPath)) {
        echo json_encode(['success' => false, 'message' => '配置文件不存在']);
        return;
    }

    $existingConfig = json_decode(file_get_contents($siteConfigPath), true);
    $partitions = $existingConfig['partitions'] ?? [];

    // 查找并删除分区
    $newPartitions = [];
    foreach ($partitions as $partition) {
        if ($partition['id'] != $id) {
            $newPartitions[] = $partition;
        }
    }

    // 如果分区数量没变，说明没找到要删除的分区
    if (count($newPartitions) == count($partitions)) {
        echo json_encode(['success' => false, 'message' => '未找到指定的分区']);
        return;
    }

    // 更新配置
    $existingConfig['partitions'] = $newPartitions;

    // 保存配置文件
    if (file_put_contents($siteConfigPath, json_encode($existingConfig, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) !== false) {
        echo json_encode(['success' => true, 'message' => '分区删除成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '分区删除失败']);
    }
}

// 处理请求
function handleRequest() {
    // 设置正确的响应头
    header('Content-Type: application/json; charset=utf-8');
    
    // 检查是否是API请求，同时支持GET和POST
    if (isset($_POST['action']) || isset($_GET['action'])) {
        $action = $_POST['action'] ?? $_GET['action'];
        switch ($action) {
            case 'get_site_config':
                getSiteConfig();
                break;
            case 'save_site_config':
                saveSiteConfig();
                break;
            case 'get_blog_list':
                getBlogList();
                break;
            case 'save_blog_list':
                saveBlogList();
                break;
            case 'get_post_content':
                getPostContent();
                break;
            case 'save_post_content':
                savePostContent();
                break;
            case 'delete_post':
                deletePost();
                break;
            case 'save_work':
            case 'update_work':
            case 'add_work':
                saveWork();
                break;
            case 'delete_work':
                deleteWork();
                break;
            case 'get_works_list':
                getWorksList();
                break;
            case 'save_works_list':
                saveWorksList();
                break;
            case 'save_partition':
                savePartition();
                break;
            case 'delete_partition':
                deletePartition();
                break;
            case 'generate_content':
                // 生成内容请求
                if (isset($_POST['type']) || isset($_GET['type'])) {
                    $type = $_POST['type'] ?? $_GET['type'];
                    initBlogSystem();
                    $blogMaker = new BlogMake();
                    try {
                        switch ($type) {
                            case 'index':
                                $path = $blogMaker->generateIndexHtml();
                                echo json_encode(['success' => true, 'message' => '首页已成功生成', 'path' => $path]);
                                break;
                            case 'posts':
                                $count = $blogMaker->generatePosts();
                                echo json_encode(['success' => true, 'message' => '帖子已成功生成', 'count' => $count]);
                                break;
                            case 'partitions':
                                $count = $blogMaker->generatePartitionHtml();
                                echo json_encode(['success' => true, 'message' => '分区已成功生成', 'count' => $count]);
                                break;
                            default:
                                echo json_encode(['success' => false, 'message' => '无效的生成请求类型！']);
                        }
                    } catch (Exception $e) {
                        echo json_encode(['success' => false, 'message' => '生成失败: ' . $e->getMessage()]);
                    }
                } else {
                    echo json_encode(['success' => false, 'message' => '未指定生成类型！']);
                }
                break;
            default:
                echo json_encode(['success' => false, 'message' => '未知的请求类型']);
        }
        exit;
    }
    
    // 检查是否有生成请求
    if (isset($_GET['make'])) {
        initBlogSystem();
        
        $make = $_GET['make'];
        $blogMaker = new BlogMake();
        
        try {
            switch ($make) {
                case 'index':
                    $path = $blogMaker->generateIndexHtml();
                    echo json_encode(['success' => true, 'message' => '首页已成功生成', 'path' => $path]);
                    break;
                case 'posts':
                    $count = $blogMaker->generatePosts();
                    echo json_encode(['success' => true, 'message' => '帖子已成功生成', 'count' => $count]);
                    break;
                case 'partitions':
                    $count = $blogMaker->generatePartitionHtml();
                    echo json_encode(['success' => true, 'message' => '分区已成功生成', 'count' => $count]);
                    break;
                default:
                    echo json_encode(['success' => false, 'message' => '无效的生成请求！']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => '生成失败: ' . $e->getMessage()]);
        }
        exit;
    }

    // 默认响应
    echo json_encode(['success' => false, 'message' => '无效的请求']);
    exit;
}

// 执行请求处理
handleRequest();
?>